import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-11-09
 * Time: 9:46
 */

public class UdpEchoServer {
    //网络编程大前提
    private DatagramSocket socket = null;

    //构造方法指定服务器端口 并创建socket实例
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    //启动服务器
    public void start() throws IOException {
        System.out.println("启动服务器!");
        //UDP 不需要建立连接 直接接收客户端发来的请求
        while (true){
            //1.读取客户端发来的请求 UDP传输的基本单位是Packet 先创建空的数据报来准备接收
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024);
            //接收发来的Packet对象 放入上面空的数据报
            socket.receive(requestPacket);
            //把发来的数据报转成String字符串
            String request = new String(requestPacket.getData(),0, requestPacket.getLength(),"utf-8");
            //根据请求计算相应
            String response = process(request);
            //3.把相应写回到客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress()); //在返回数据报中 要指明返回客户端的地址
            //发送给客户端
            socket.send(requestPacket);
            System.out.printf("[%s:%d] req: %s,resp: %s\n",requestPacket.getAddress().toString(),
                    requestPacket.getPort(),request,response);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
